package com.example.myspace.control.Image;

import com.alibaba.fastjson.JSONObject;
import com.example.myspace.mapper.ImageMapper;
import com.example.myspace.pojo.Image;
import com.example.myspace.pojo.User;
import com.example.myspace.service.user.util.UserDetailsImpl;
import com.fasterxml.jackson.databind.ser.std.MapSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
public class upImageControl {
    public static String filePath = "target/classes/static/Image";

    static {
        filePath = System.getProperty("user.dir") + "/" + filePath;
    }

    @Autowired
    private ImageMapper imageMapper;

    @PostMapping("/myspace/upImage/")
    public Map<String, String> getImage(HttpServletRequest request){
        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");

        System.out.println(filePath);
        File file1 = new File(filePath);
        if(!file1.exists()){
            file1.mkdirs();
        }
        // 获取文件真实姓名
        String fileName = file.getOriginalFilename();
        System.out.println(file);
        Map<String, String> res = new HashMap<>();
        String suffixName = fileName.substring(fileName.lastIndexOf('.') + 1);
        System.out.println(suffixName);
        if(suffixName.equals("jpg")  || suffixName.equals("png") || suffixName.equals("jpeg")) {
            String name = String.valueOf(UUID.randomUUID());
            String path = filePath + "/" + name + "." + suffixName;

            try {
                // 将文件信息保存到指定文件夹目录
                file.transferTo(new File(path));
                res.put("error", "上传成功");
                name = name + "." + suffixName;

                res.put("message", name);
            } catch (IOException e) {
                res.put("error", "上传失败");
                e.printStackTrace();
            }finally {
                return res;
            }
        }else{
            res.put("error", "上传文件不符合要求");
            return res;
        }
    }

    @GetMapping("/myspace/getImage/")
    public JSONObject getImage(@RequestParam Map<String,String> map){
        Integer index = Integer.valueOf(map.get("index"));
        JSONObject resp = new JSONObject();
        List<File> files = Arrays.asList(new File(filePath).listFiles());
        Collections.sort(files, new Comparator<File>(){
            public int compare(File file, File newFile){
                if(file.lastModified() < newFile.lastModified()){
                    return 1;
                }else if(file.lastModified() == newFile.lastModified()){
                    return 0;
                }else{
                    return  -1;
                }
            }
        });
        List<String> times = new ArrayList<>();
        int startTotal = index == 1 ? 0 : index * 8;
        int endTotal = index == 1 ? 16 : index * 8 + 8;
        for(int i = startTotal; i < endTotal && i < files.size(); i++){
            times.add(files.get(i).getName());
        }
        resp.put("message", times);
        resp.put("titalpages", files.size());
        return resp;
    }

    @GetMapping("/myspace/deleteImage/")
    public String deleteImage(@RequestParam Map<String, String> map){
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User user = loginUser.getUser();
        if(user.getType() != 1){
            return "not have power";
        }

        String name = map.get("name");
        File file = new File(filePath + "/" + name);
        if(file.exists()){
            file.delete();
            return  "success";
        }else{
            return "not found";
        }

    }
}
